package sky.wicket;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sky.domain.Country;
import sky.service.CountryService;

/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 17.11.13
 * Time: 18:12
 * To change this template use File | Settings | File Templates.
 */
public class AddUpdateCountry extends BasePage {

    @SpringBean
    private CountryService countryService;

    private Country country;
    private boolean createFlag = false;
    private boolean updateFlag = false;
    static final Logger log = LoggerFactory.getLogger(AddUpdateCountry.class);

    public AddUpdateCountry() {
        this.country = new Country();
        createFlag = true;
        addElementsToPage();
    }

    public AddUpdateCountry(String countryName) {
        this.country = countryService.getByName(countryName, false);
        updateFlag = true;
        addElementsToPage();
    }

    private void addElementsToPage() {
        Form<Country> newCountryForm = new Form<Country>("newCountryForm", new CompoundPropertyModel<Country>(country)) {

            @Override
            protected void onSubmit() {
                log.info("Submitting Form...");
                log.info("Information From Form:");
                log.info("   Country's Name: " + country.getName());
                createOrUpdate();
            }

            @Override
            protected void onError() {}
        };
        newCountryForm.add(new TextField<String>("name").setRequired(true));
        newCountryForm.add(new Label("countryNameLabel", "Country: "));
        newCountryForm.add(new TextField<String>("capital").setRequired(true));
        newCountryForm.add(new Label("capitalNameLabel", "Capital: "));
        add(newCountryForm);
        add(new FeedbackPanel("feedback"));
    }

    private void createOrUpdate() {
        log.info("Checking Flags...");
        log.info("Create Flag: " + createFlag);
        log.info("Update Flag: " + updateFlag);
        if (createFlag) {
            countryService.add(country);
            return;
        }
        if (updateFlag) {
            countryService.edit(country);
            return;
        }
    }
}
